import Vue from 'vue'
import Router from 'vue-router'
import LayoutIndex from '@/views/layout/index.vue'
import SearchIndex from '@/views/search/index.vue'
import SearchList from '@/views/search/list.vue'
import ProDetailIndex from '@/views/prodetail/index.vue'
import PayIndex from '@/views/pay/index.vue'
import LoginIndex from '@/views/login/index.vue'
import MyOrderIndex from '@/views/myorder/index.vue'
import HomeIndex from '@/views/layout/home.vue'
import CategoryIndex from '@/views/layout/category.vue'
import CartIndex from '@/views/layout/cart.vue'
import UserIndex from '@/views/layout/user.vue'
import store from '@/store/store'
Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      component: LoginIndex
    },
    {
      path: '/',
      component: LayoutIndex,
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: HomeIndex
        },
        {
          path: '/category',
          component: CategoryIndex
        },
        {
          path: '/cart',
          component: CartIndex
        },
        {
          path: '/user',
          component: UserIndex
        }
      ]
    },
    {
      path: '/search',
      component: SearchIndex
    },
    {
      path: '/SearchList',
      component: SearchList
    },
    {
      path: '/prodetail/:id',
      component: ProDetailIndex
    },
    {
      path: '/pay',
      component: PayIndex
    },
    {
      path: '/myorder',
      component: MyOrderIndex
    }
  ]
})

const authRoutes = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  if (!authRoutes.includes(to.path)) {
    next()
    return
  }
  const token = store.state.user.userInfo.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
